from strategy.StrategyTemplate import StrategyTemplate
from utils.jsl_data_map import pre_columns_map, pre_default_columns
from strategy import strategy_filter
from sqlalchemy import create_engine
# from database.lhjy import engine
import pandas as pd
from utils.pd_show_utils import *
from utils.utils import add_pre
import akshare as ak
import numpy as np
import math

"""
抢权配售
"""


def retrun_type(code):
    if code[0:3] == '688':
        return "沪科创板"
    elif code[0:2] == '30':
        return "深创业板"
    elif code[0:2] == '60':
        return "沪主板"
    elif code[0:2] == '00':
        return "深主板"


def retrun_stock_percent(code):
    pre_code = add_pre(code)
    stock_hold = ak.stock_gdfx_top_10_em(symbol=pre_code, date='20230331')
    if stock_hold is not None:
        stock_hold_percent = stock_hold.loc[stock_hold['占总股本持股比例'] >= 5.0]['占总股本持股比例'].sum()
        return stock_hold_percent
    else:
        return 0


class BondPre(StrategyTemplate):
    """
    配债策略
    """

    def __init__(self):
        super(self.__class__, self).__init__()
        self.strategy_name = "配债策略"
        self.strategy_descrption = "配债策略"
        # self.data = pre
        # self.data = self.data.rename(columns=pre_columns_map)
        # print(self.data_tool)

    def run(self):
        # pass
        # 获得默认列

        self.data = self.data[pre_default_columns]
        self.data = self.data.loc[self.data['发债进展'].astype(int) >= 80]
        self.data = self.data.loc[self.data['标记'] != "C"]
        self.data['类型'] = self.data['正股代码'] \
            .apply(retrun_type)
        self.data['进度名称'] = self.data['进度名称'].astype(str) \
            .apply(lambda x: x.split('<br>')[0])

        self.data['5%以上股东持股比例'] = self.data['正股代码'] \
            .apply(retrun_stock_percent) \
            .apply(lambda x: format(x, '.2f'))
        self.data['全额配售后规模'] = ((100 - self.data['5%以上股东持股比例'].astype(float)) /
                                100 * self.data['发行规模(亿元)'].astype(float)) \
            .apply(lambda x: format(x, '.2f'))

        self.data['安全垫(按120元计算)'] = (200 / self.data["配售10张所需股数"] / self.data["正股价"] * 100) \
            .apply(lambda x: format(x, '.2f'))
        self.data['沪债一手党股数'] = np.where((self.data["类型"] == '沪主板') | (self.data["类型"] == '沪科创板'),
                                        (self.data["配售10张所需股数"] * 0.6).astype(int),
                                        0)
        self.data['沪债一手党股数'] = self.data['沪债一手党股数'].apply(lambda x: math.ceil(x / 100) * 100)

        self.data['沪债一手党所需资金'] = np.where((self.data["类型"] == '沪主板') | (self.data["类型"] == '沪科创板'),
                                          (self.data['正股价'] * self.data['沪债一手党股数']).apply(lambda x: format(x, '.2f')),
                                          0)

        self.data['沪债一手党安全垫'] = np.where((self.data["类型"] == '沪主板') | (self.data["类型"] == '沪科创板'),
                                         (200 / self.data["沪债一手党股数"] / self.data["正股价"] * 100).apply(
                                             lambda x: format(x, '.2f')), 0)

        self.data['配售10张实际所需股数'] = self.data['配售10张所需股数'].apply(lambda x: math.ceil(x / 100) * 100)
        self.data['配售10张所需资金'] = (self.data['正股价'] * self.data['配售10张实际所需股数']) \
            .apply(lambda x: format(x, '.2f'))

        # 清掉原来的索引
        self.data.reset_index(inplace=True, drop=True)
        # 1000 * 100 / 百元含权 / 正股价 -> 配售一手所需股数

    def api(self,
            db,
            table_name="pd_pre",
            filter_base_flag=True,
            fill_na_flag=True):
        # 获得默认列
        self.data = pd.read_sql_table('pd_pre', con=db.engine)
        self.data = self.data[pre_default_columns]
        # 发债进展大于等于80
        self.data = self.data.loc[self.data['progress'].astype(int) >= 80]
        # E->待上市 B->待申购 A->申购日(打新日) C->已申购 N->未申购
        self.data = self.data.loc[self.data['ap_flag'] != "C"]
        # 属于哪个板块 后端不计算了 改由计算属性实现
        self.data['market_type'] = self.data['stock_id'].apply(retrun_type)
        self.data['progress_nm'] = self.data['progress_nm'].astype(str). \
            apply(lambda x: x.split('<br>')[0])
        # 计算大股东全额赔售后规模
        self.data['best_orig_iss_amt'] = ((100 - self.data['big_stockholder'].astype(float)) /
                                          100 * self.data['amount'].astype(float)).apply(lambda x: format(x, '.2f'))
        # 上市后按照120元计算出的安全垫
        self.data['safety_pad_by_120'] = (200 / self.data["apply10"] / self.data["price"] * 100)\
            .apply(lambda x: format(x, '.2f'))
        # 计算沪债一手党股数
        self.data['sh_one_hand_stock_num'] = np.where((self.data["market_type"] == '沪主板') | (self.data["market_type"] == '沪科创板'),
                                        (self.data["apply10"] * 0.6).astype(int), 0)
        self.data['sh_one_hand_stock_num'] = self.data['sh_one_hand_stock_num'].apply(lambda x: math.ceil(x / 100) * 100)
        # 计算沪债一手党资金
        self.data['sh_one_hand_money'] = np.where((self.data["market_type"] == '沪主板') | (self.data["market_type"] == '沪科创板'),
                                                  (self.data['price'] * self.data['sh_one_hand_stock_num']).
                                                  apply(lambda x: format(x, '.2f')), 0)
        # 沪债一手党安全垫
        self.data['sh_one_hand_safety_pad'] = np.where((self.data["market_type"] == '沪主板') | (self.data["market_type"] == '沪科创板'),
                                                       (200 / self.data["sh_one_hand_stock_num"] / self.data["price"] * 100)
                                                       .apply(lambda x: format(x, '.2f')), 0)
        # 配售10张实际所需股数
        self.data['apply10_reality'] = self.data['apply10'].apply(lambda x: math.ceil(x / 100) * 100)
        # 配售10张实际所需资金
        self.data['apply10_reality_money'] = (self.data['price'] * self.data['apply10_reality'])\
            .apply(lambda x: format(x, '.2f'))

        # 清掉原来的索引
        self.data.reset_index(inplace=True, drop=True)
        self.data = self.data.fillna('NONE')

        # 1000 * 100 / 百元含权 / 正股价 -> 配售一手所需股数
        return self.data

if __name__ == '__main__':
    '''
    ins = ThreeLowRollWeek()
    ins.topN = -1
    ins.test()
    '''
    ins = BondPre()
    ins.topN = -1
    ins.run()
    df_table(ins.data[:ins.topN], 'index')
    del ins.data['发债进展']
    del ins.data['标记']

    ins.data = ins.data[['正股代码', '类型', '正股名称', '正股价', '转债名称',
                         '进度名称', '发行规模(亿元)', '全额配售后规模',
                         '5%以上股东持股比例', '配售10张所需股数', '配售10张实际所需股数', '配售10张所需资金',
                         '安全垫(按120元计算)', '沪债一手党股数', '沪债一手党所需资金', '沪债一手党安全垫',
                         '每股配售(元)', '百元股票含权(元)', '股权登记日', '申购日']]
    ins.data.to_excel('配债.xlsx', index=None)

    # stock_hold = ak.stock_gdfx_top_10_em(symbol='sh688711',date='20230724')
    # print(stock_hold)
